#!/bin/bash
########################################################################
# script name:  sync_keys.sh
# Used for:     Syncing ssh keys everywhere
# Author:       Martin Dumont
# Contributors:
# Version:      0.1
#
# (date format: date +'%Y/%m/%d')
#
# Date          Version Contributors    Modifications
# ----------    ------- ------------    -------------
# 2011/04/06    0.1     MDUMONT         initial
# 2011/04/07    1.o     MDUMONT         official release
########################################################################
usage()
{
cat << STOP

usage: $0 [options] [ARG]

This script is used for ....

OPTIONS:
   -h               Comma seperated list of hosts, or ALL
   -u               Comma seperated list of users
   -c               Clear existing authorized_keys before editing (cleanup)

Ex.:
$0 -h saprmt02
$0 -h saprmt02,saprmt01 -c
$0 -h ALL

STOP
}
#######################################
# Get parameters
#######################################
while getopts h:u:c OPTION
do
        case $OPTION in
        h)
                HOSTS=$(echo $OPTARG | tr [:upper:] [:lower:] | sed 's/,/ /g')
                ;;
        u)
                USERLIST=$(echo $OPTARG | tr [:upper:] [:lower:] | sed 's/,/ /g')
                ;;
        c)
                CLEAR=on
                ;;
        \?)
                usage
                exit 1
                ;;
        *)
                usage
                exit 1
                ;;
        esac
done
if [ $OPTIND = 1 ]; then usage; exit 1; fi
if [ -z "$HOSTS" ]; then echo "Specify a host..."; usage; exit 1; fi
if [ -z "$USERLIST" ]; then USERLIST=$USER; fi
#if [ ! -z "CLEAR" ]
#then
#	read -p "Are you sure you want to CLEAR the remote authentification file (default no)? [y/n] " -e a1
#	if [ "$a1" != "y" ]; then echo "Exiting."; exit 1; fi
#fi
#######################################
# Functions
#######################################
function checkhost {
	ENVSCRIPT=/usr/local/scripts/env
	if [[ -f $ENVSCRIPT ]]; then . $ENVSCRIPT; else echo "No env library ($ENVSCRIPT)"; exit 1; fi
	if [ "$HOSTS" = "all" ]; then HOSTS=$(list_hosts_all | xargs); fi
	for HOSTNAME in $HOSTS
	do
		echo -e "Pinging host $HOSTNAME ... \c"
		PING=$(ping -c 1 -w 1 $HOSTNAME 2> /dev/null)
  	      RC=$?
  	      if [[ $RC = 0 ]]
		then
			echo "ok"
			NEWHOSTLIST="$NEWHOSTLIST $HOSTNAME"	
		else
			echo "Host $HOSTNAME not pingable, skipping..."
		fi
	done
	NEWHOSTLIST=$(echo $NEWHOSTLIST | sed 's/^ //')
}
function check_identity {
	ID_FILE="`cat /etc/passwd | grep "^$1" | cut -d: -f6`/.ssh/id_rsa.pub"
	if [ ! `sudo -u $1 ls -1 $ID_FILE 2> /dev/null` ]
	then 
		echo "$0: ERROR: File $ID_FILE not found" >&2	
	else
		GET_ID="cat ${ID_FILE}"
		if [ -z "`eval $GET_ID`" ]; then
			echo "$0: ERROR: No identities found" >&2
		else
			echo -e "Verifying Public key $ID_FILE ... \c"
			sudo -u $1 ssh-keygen -B -f $ID_FILE 2>&1 > /dev/null
			RC=$?
			if [ $RC = 0 ]; then echo ok; else NOT_OK; fi
		fi
	fi
}
#######################################
# MAIN
#######################################
checkhost
for TGUSER in $USERLIST
do
	check_identity $TGUSER | grep -q ok
	RC=$?
	if [[ $RC = 0 ]]
	then
		for HOSTNAME in $NEWHOSTLIST
		do
			echo -e "Syncing public key from $HOST to $TGUSER on $HOSTNAME ... \c"
			if [ "$CLEAR" = "on" ]
			then
				{ eval "$GET_ID" ; } | sudo -u saunix ssh -o "BatchMode yes" -q saunix@$HOSTNAME "sudo -u $TGUSER sh -c 'test -d ~$USER/.ssh || sudo mkdir -m 700 ~$TGUSER/.ssh ; cat > ~$TGUSER/.ssh/authorized_keys; sudo chmod 600 ~$TGUSER/.ssh/authorized_keys; sudo chown -R $TGUSER ~$TGUSER/.ssh' && echo ok" || echo "Login failed"
			else
				{ eval "$GET_ID" ; } | sudo -u saunix ssh -o "BatchMode yes" -q saunix@$HOSTNAME "sudo -u $TGUSER sh -c 'test -d ~$TGUSER/.ssh || mkdir -m 700 ~$TGUSER/.ssh ; cat >> ~$TGUSER/.ssh/authorized_keys; chmod 600 ~$TGUSER/.ssh/authorized_keys; chown -R $TGUSER ~$TGUSER/.ssh' && echo ok" || echo "Login failed"
			fi
		done
	fi
done
#######################################
exit 0
